<template>
  <section class="section-box">
    <van-sticky class="report-nav-bar">
      <van-nav-bar @click-left="goBack" left-arrow placeholder>
        <template #title>
          <van-tabs v-model:active="activeTabRef" @change="changeTab">
            <van-tab name="report" title="汇报关系" />
            <van-tab name="organization" title="组织架构" />
          </van-tabs>
        </template>
      </van-nav-bar>
      <div class="search-box">
        <CommonSearch
          v-model:search-keyword="searchKeyword"
          v-model:loading="searchLoading"
          placeholder="搜索姓名或者工号"
          :finished="searchFinished"
          :suggest-list="suggestList"
          @onSearchFn="onSearchFn"
          @onSearchValChange="onSearchValChange"
          @onSelectItem="onSelectItem"
          @onLoadMore="onLoadMore"
        ></CommonSearch>
      </div>
    </van-sticky>
    <template v-if="emptyListMessage">
      <div class="manager-box ly-border-card">
        <van-empty :description="emptyListMessage" />
      </div>
    </template>
    <template v-else>
      <div class="manager-box ly-border-card">
        <van-skeleton title :row="2" :loading="managerListLoading">
          <p class="title">上级</p>
          <ul class="manager-ul hx-scroll">
            <li class="flex-li" v-for="item in managerListRef" :key="item.id">
              <div class="li-left">
                <i class="iconfont icon-shangji"></i>
              </div>
              <div
                style="cursor: pointer"
                class="li-center van-ellipsis"
                @click="onSelectLeader(item)"
              >
                <p class="leader-info">
                  <span>{{ item.leadername }}</span>
                  <span>（{{ item.workcode }}）</span>
                </p>
                <p class="depart-info">
                  <span style="margin-right: 10px">{{
                    item.parentdepart
                  }}</span>
                  <span>{{ item.workposition }}</span>
                </p>
              </div>
              <div class="li-right">By{{ item.worktype }}</div>
            </li>
          </ul>
        </van-skeleton>
      </div>
      <div class="ly-border-card" style="margin-top: 10px">
        <van-skeleton title :row="2" :loading="managerListLoading">
          <div class="person-info">
            <div class="flex-li">
              <div class="li-left">
                <i class="iconfont icon-zhutiren"></i>
              </div>
              <div class="li-center">
                <p class="leader-info">
                  <span>{{ personInfoRef.name }}</span>
                  <span>（{{ personInfoRef.workcode }}）</span>
                  <!-- <van-tag
                    style="
                      cursor: pointer;
                      border-radius: 10px;
                      font-weight: 400;
                    "
                    round
                    color="#fee9dd"
                    text-color="#383838"
                    size="medium"
                    @click.stop="jumpToPersonal(personInfoRef.workcode)"
                    >查看档案</van-tag
                  > -->
                </p>
              </div>
              <div class="li-right">
                管辖人数：{{ personInfoRef.leadpeople }}人
              </div>
            </div>
            <div class="flex-li">
              <div class="li-left" style="visibility: hidden">
                <i class="iconfont icon-zhutiren"></i>
              </div>
              <div class="li-center van-ellipsis">
                <p style="font-size: 12px">
                  <span style="margin-right: 10px">{{
                    personInfoRef.departname
                  }}</span>
                  <span>{{ personInfoRef.workposition }}</span>
                </p>
              </div>
              <div class="li-right">
                直线下属：{{ personInfoRef.directlypeople }}人
              </div>
            </div>
          </div>
        </van-skeleton>
      </div>
    </template>

    <div class="scoped-box ly-border-card">
      <p class="title">管辖范围:</p>
      <div class="scoped-tree-box hx-scroll">
        <el-tree
          class="hx-scroll"
          :class="{ 'is-mobile': isMobile }"
          :data="scopedTreeDataRef"
          :empty-text="treeLoading ? '加载中...' : '暂无管辖人员'"
          :props="{ children: 'children', label: 'label' }"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <!-- 员工 -->
              <template v-if="data.otype === 'P'">
                <div class="node-content">
                  <span>{{ node.label }}</span>
                  <span style="font-size: 12px">
                    （
                    <span v-if="data.workposition" style="margin-right: 10px"
                      >岗位：{{ data.workposition }}</span
                    >
                    <span v-if="data.departname" style="margin-right: 10px"
                      >部门：{{ data.departname }}</span
                    >
                    <span>工号：{{ data.code }}</span>
                    ）
                  </span>
                </div>
              </template>
              <template v-else>
                <span>{{ node.label }}</span>
                <span>（{{ data.count }}人）</span>
                <van-tag
                  style="margin-left: 4px"
                  v-if="data.leadername"
                  plain
                  type="primary"
                >
                  <span>部门负责人：{{ data.leadername }}</span>
                  <span v-if="data.zjg">（{{ data.zjg }}）</span>
                </van-tag>
              </template>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <van-back-top right="20" bottom="20" />
  </section>
</template>

<script setup>
import {
  ref,
  onActivated,
  nextTick,
  watch,
  getCurrentInstance,
  computed,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { usePublicStore } from "@/stores/publicInfo";
import sapRequest from "@/api/sapRequest";
import { useUserStore } from "@/stores/userInfo";
import CommonSearch from "@/components/CommonSearch.vue";
const { proxy } = getCurrentInstance();
const publicStore = usePublicStore();
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const isMobile = computed(() => publicStore.isMobile);
const reportId = ref("");
const activeTabRef = ref("report");
//搜索相关
const searchKeyword = ref("");
//点击查询按钮
const onSearchFn = proxy.$utils.debounce((searchVal) => {
  if (!searchVal) {
    showToast("请输入查询关键词");
    return;
  }
  showLoadingToast({
    message: "查询中...",
    forbidClick: true,
    duration: 0,
  });
  const params = {
    IM_SYSID: "YDHBX", //系统标识，移动端汇报关系固定为YDHBX
    IM_OBJID: searchKeyword.value,
    IM_DATE: publicStore.searchDateStr,
    IM_PAGE: 1,
    IM_PGNUM: pageSizeRef.value,
    IM_PERNR: userStore.userid, // 当前登录人工号 用于权限控制
  };
  sapRequest
    .search(params)
    .then((res) => {
      if (Array.isArray(res) && res.length) {
        const { result = [] } = res[0];
        if (result.length) {
          const searchResult = result[0]["data"] || [];
          if (searchResult.length) {
            checkAuthority(searchResult[0]);
          } else {
            showToast("查询完毕，但没有匹配到结果。");
          }
        }
      } else {
        showToast("查询完毕，但没有匹配到结果。");
      }
    })
    .catch((error) => {
      showToast(error.message || "查询完毕，但没有匹配到结果。");
    });
}, 500);
//联想搜索逻辑
const searchLoading = ref(false);
//是否最后一页
const searchFinished = computed(() => {
  return pageNumRef.value >= pageCountRef.value;
});
const pageNumRef = ref(1);
const pageSizeRef = ref(10);
const pageCountRef = ref(0); //总共有多少页
const suggestList = ref([]);
// 输入框变化
async function onSearchValChange(val) {
  if (val === "") {
    suggestList.value = [];
    return;
  }
  suggestList.value = [];
  pageNumRef.value = 1;
  if (searchRequestId.value) {
    sapRequest.handleCancelRequest(searchRequestId.value, "手动取消请求");
    searchRequestId.value = "";
  }
  suggestList.value = await handleSearch();
}
//选中对应联想搜索条目
function onSelectItem(item) {
  const { data } = item;
  if (data && data.length) {
    checkAuthority(data[0]);
  }
}
// 模糊查询加载更多联想搜索内容
async function onLoadMore() {
  searchLoading.value = true;
  if (!searchFinished.value) {
    const moreData = await handleSearch({ IM_PAGE: ++pageNumRef.value });
    suggestList.value = suggestList.value.concat(moreData);
    nextTick(() => {
      searchLoading.value = false;
    });
  }
}

//查询请求id 用于手动取消请求
const searchRequestId = ref("");
//模糊查询通用函数
function handleSearch(outerParams = {}) {
  return new Promise((resoleve, reject) => {
    const params = {
      IM_SYSID: "YDHBX", //系统标识，移动端汇报关系固定为YDHBX
      IM_DATE: publicStore.searchDateStr,
      IM_OBJID: searchKeyword.value,
      IM_PAGE: 1,
      IM_PGNUM: 10,
      IM_PERNR: userStore.userid, // 当前登录人工号 用于权限控制
      ...outerParams,
    };
    searchRequestId.value = `search_${Date.now()}`;
    sapRequest
      .search(params, true, searchRequestId.value)
      .then((res) => {
        //后台格式是这样 我只能兼容了。。。
        if (Array.isArray(res) && res.length) {
          const { rpage, result } = res[0];
          if (result.length) {
            pageCountRef.value = rpage || 0;
            //这里后台返回的格式，需要前端处理一下
            console.log(result, "result");
            const finalArray = result.map((el) => {
              return {
                ...el,
                label: Array.isArray(el.data)
                  ? proxy.$utils.highlightText(
                      el.data.map(
                        (sub) => `${sub.name} / ${sub.id} / ${sub.orgeht}`
                      ),
                      params.IM_OBJID
                    )
                  : "",
              };
            });
            resoleve(finalArray);
          }
        } else {
          resoleve([]);
        }
      })
      .catch((error) => {
        reject(error);
        console.error(error.message);
      });
  });
}

const managerListRef = ref([]);
const personInfoRef = ref({});
const managerListLoading = ref(false);
const emptyListMessage = ref("");
const scopedTreeDataRef = ref([]);
const treeLoading = ref(false);
watch(
  () => route.params.rid,
  (newId, oldId) => {
    if (newId && newId !== oldId && newId !== reportId.value) {
      nextTick(() => {
        reportId.value = newId;
        //记录当前汇报人id
        publicStore.setReportId(newId);
        getReportInfo(newId);
      });
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
//根据工号获取汇报人、汇报人上下级关系、管辖范围
function getReportInfo(workNo) {
  emptyListMessage.value = "";
  showLoadingToast({
    message: "查询中...",
    forbidClick: true,
    duration: 0,
  });
  const data = {
    IM_OBJID: workNo, //查询工号
    IM_DATE: publicStore.searchDateStr, //查询日期
    IM_SYSID: "YDHBX", //系统标识，移动端汇报关系固定为YDHBX
    IM_PERNR: userStore.userid, // 当前登录人工号 用于权限控制
  };
  managerListLoading.value = true;
  treeLoading.value = true;
  sapRequest
    .reportInfo(data)
    .then((res) => {
      if (res.status === "E") {
        showFailToast(res.message);
        emptyListMessage.value = res.message;
        scopedTreeDataRef.value = [];
      } else {
        if (Array.isArray(res) && res.length) {
          const { hbsj, hbztr, gxfw } = res[0];
          //汇报上级
          managerListRef.value = proxy.$utils.sortBy(hbsj || [], {
            desc: false,
            compareFn: (a, b) => {
              const priorityName = "组织架构";
              const aIsPriority = a.worktype === priorityName;
              const bIsPriority = b.worktype === priorityName;

              //组织架构排在前面
              if (aIsPriority && !bIsPriority) return -1;
              if (!aIsPriority && bIsPriority) return 1;
              return 0;
            },
          });
          // 汇报主体人
          personInfoRef.value = hbztr || {};
          //管辖范围
          scopedTreeDataRef.value = proxy.$utils.arrayToTree(gxfw) || [];
          console.log(managerListRef.value, "managerListRef");
          console.log(scopedTreeDataRef.value, "scopedTreeDataRef");
        } else {
          showFailToast("查询失败!");
          emptyListMessage.value = "查询失败！";
        }
      }
    })
    .catch((error) => {
      scopedTreeDataRef.value = [];
      emptyListMessage.value = error.message || "查询失败";
      showFailToast(error.message || "查询失败");
    })
    .finally(() => {
      managerListLoading.value = false;
      treeLoading.value = false;
      closeToast();
    });
}
function handleNodeClick(data) {
  const { otype, authority, code, label } = data;
  if (otype === "P") {
    if (authority) {
      if (code) {
        searchKeyword.value = "";
        suggestList.value = [];
        router.push({
          path: `/report/${code}`,
        });
      }
    } else {
      showToast({
        message: `您没有 ${label}(${code}) 的查看权限`,
        duration: 2000,
      });
    }
  }
}
function goBack() {
  router.go(-1);
}
function changeTab(tabName) {
  if (tabName === "organization") {
    const organizationId = publicStore.organizationId;
    if (organizationId) {
      router.push({
        path: `/organization/${organizationId}`,
      });
    } else {
      router.push({
        path: "/",
      });
    }
  }
}
function checkAuthority(item) {
  const { authority, id, name, orgeht } = item || {};
  //是否有权限
  if (authority) {
    if (id) {
      searchKeyword.value = "";
      suggestList.value = [];
      router.push({
        path: `/report/${id}`,
      });
    }
  } else {
    emptyListMessage.value = `您没有 ${name}/${id}/${orgeht} 的查看权限`;
    showToast({
      message: emptyListMessage.value,
      duration: 2000,
    });
  }
}
//点击上级领导
function onSelectLeader(item) {
  const { workcode } = item;
  const params = {
    IM_SYSID: "YDHBX", //系统标识，移动端汇报关系固定为YDHBX
    IM_OBJID: workcode,
    IM_DATE: publicStore.searchDateStr,
    IM_PAGE: 1,
    IM_PGNUM: pageSizeRef.value,
    IM_PERNR: userStore.userid, // 当前登录人工号 用于权限控制
  };
  sapRequest
    .search(params)
    .then((res) => {
      if (Array.isArray(res) && res.length) {
        const { result = [] } = res[0];
        if (result.length) {
          const searchResult = result[0]["data"] || [];
          if (searchResult.length) {
            checkAuthority(searchResult[0]);
          } else {
            showToast("查询权限数据失败");
          }
        }
      } else {
        showToast("查询权限数据失败");
      }
    })
    .catch((error) => {
      showToast(error.message || "查询权限数据失败");
    });
}

//查看指定工号的员工档案
function jumpToPersonal(pid) {
  if (pid) {
    router.push({
      path: `/personal/${pid}`,
    });
  }
}
onActivated(() => {
  activeTabRef.value = "report";
});
</script>

<style lang="scss" scoped>
.section-box {
  padding-bottom: 20px;
  .report-nav-bar {
    :deep(.van-sticky) {
      border-radius: 6px;
      background-color: #ffffff;
      // overflow: hidden;
    }
    //产品要求 标题居中显示
    :deep(.van-nav-bar) .van-nav-bar__title {
      margin-left: 40%;
    }
  }
  .search-box {
    padding: 10px;
  }
  // .search-box {
  //   display: flex;
  //   align-items: center;
  //   padding: 0 10px;
  //   .van-search {
  //     flex: 1;
  //     padding-left: 0px;
  //   }
  // }

  .manager-box {
    margin-top: 10px;
    .title {
      font-size: 14px;
      font-weight: 600;
    }
    .manager-ul {
      margin-top: 20px;
      padding-right: 10px;
    }
  }
  .person-info {
    background-color: #fef8f4;
    padding: 10px 10px 10px 0px;
    .flex-li {
      align-items: center;
    }
  }
  .flex-li + .flex-li {
    margin-top: 10px;
  }
  .flex-li {
    display: flex;
    align-items: flex-start;
    .li-center {
      margin: 0 10px;
      flex: 1;
      width: 1px;
      .leader-info {
        font-size: 14px;
        span {
          font-weight: 600;
        }
      }
      .depart-info {
        margin-top: 8px;
        font-size: 12px;
      }
    }
    .li-right {
      font-size: 12px;
    }
  }

  .scoped-box {
    margin-top: 10px;
    .title {
      font-weight: 600;
    }
    .scoped-tree-box {
      margin-top: 10px;
      .el-tree {
        overflow: auto;

        :deep(.el-tree-node__content) {
          margin-bottom: 6px;
        }
      }
      .is-mobile {
        :deep(.el-tree-node > .el-tree-node__children) {
          overflow: unset !important;
        }
      }
    }
  }
}
</style>